import { createStore } from 'vuex'
import {setMenu} from "../router";

interface stateType {
  logged: boolean;
  token: string | null;
  userType: string | null;
  username: string | null;
}
// 当前登录状态
const logged = localStorage.getItem('logged') ? true : false;
// 获取token
const token = localStorage.getItem('token') ? localStorage.getItem('token') : '';
// 获取用户级别
const userType = localStorage.getItem('userType') ? localStorage.getItem('userType') : '';
// 获取用户名
const username = localStorage.getItem('username') ? localStorage.getItem('username') : '';
// 调用获取菜单API
userType && setMenu(userType);
// 创建一个新的 store 实例
const store = createStore({
  state ():stateType {
    return {
      // 登录状态
      logged,
      // token信息
      token,
      // 用户级别
      userType,
    //  用户名
      username,
    }
  },
  mutations: {
    setLogged(state:stateType, logged:boolean) {
      state.logged = logged;
      localStorage.setItem('logged', 'true');
    },
    setToken(state:stateType, token:string) {
      state.token = token;
      localStorage.setItem('token', token);
    },
    setUserType(state:stateType, userType:string) {
      state.userType = userType;
      localStorage.setItem('userType', userType);
    },
    setUsername(state:stateType, username: string) {
      state.username = username;
      localStorage.setItem('username', username);
    }
  },
  actions: {},
});

export default store;
